import React from 'react';
import { connect } from 'react-redux'
import {Button, Table,} from 'antd';
import PurchaseHistoryService from 'containers/purchase-history/purchase-history.service'
import {messages, simplifyDataSource, formatNumber} from "share/common";
import moment from "moment";

class PurchaseHistory extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      page: 0,
      pagination: {
        total: 0,
      },
      columns: [],
    }
  }


  componentWillMount() {
    this.renderDataSource();
  }


  renderDataSource = () => {
    let dataSource = [
      {itemName: messages('basic-16.key180')/*产品规格*/},
      {paidtimeDate: messages('basic-16.key181')/*购买时间*/,
        render: text => {return text ? moment(text).format("YYYY-MM-DD") : null}},
      {subQuantity: messages('basic-16.key182')/*购买量（人）*/},
      {channel: messages('basic-16.key183')/*购买渠道*/},
      {payFee: messages('basic-16.key184')/*交易金额（元）*/,
        render: (text) => text === undefined || text === null ? "-" : `${formatNumber(text)}`}
    ];
    let columns = simplifyDataSource(dataSource,);
    this.setState({
      columns
    }, () => {
      this.getTableData();
    })
  };

  //获取映射关系
  getTableData = () => {
    const {page} = this.state;
    this.setState({
      loading: true,
    });
    PurchaseHistoryService.getTableData(page).then(res => {
        this.setState({
          data: res.data,
          loading: false,
          pagination: {
            total: Number(res.headers['x-total-count']),
            current: this.state.page + 1,
            onChange: this.onChangePaper,
          }
        })
      }
    ).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };

  //点击分页
  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({
          page: page - 1,
        }, () => {
          this.getTableData();
        }
      )
    }
  };

  render (){
    const {pagination, loading, data, columns, } = this.state;
    return(
      <div>
        <div style={{margin: "10px 0"}}>
          {messages('basic-16.key185',{arg1: pagination.total||0})/*共搜索到 ${`{arg1}`} 条数据*/}
        </div>
        <Table rowKey='id'
               loading={loading}
               dataSource={data}
               columns={columns}
               pagination={pagination}
               size="middle"
               bordered/>
      </div>
    )
  }
}


PurchaseHistory.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
  }
}


export default connect(mapStateToProps)(PurchaseHistory);
